package com.peanut.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @className: com.peanut.controller-> FileController
 * @description: 文件上传和下载功能。自定义响应体。
 * @author: chenhs
 * @createDate: 2021-08-31 22:20
 * @version: 1.0
 */
@Controller
public class FileController {
    @GetMapping("/testResponseEntiity")
public ResponseEntity<byte[]> testResponseEntitiy(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取 session
        HttpSession session = request.getSession();
//        获取 应用上下文对象
        ServletContext context = session.getServletContext();
//        获取资源在服务器中的绝对路径
        String realPath = context.getRealPath("/static/js/vue/vue.js");
//        创建输入流流存放资源
        FileInputStream inputStream = new FileInputStream(realPath);
//        创建字节数组
        byte[] bytes = new byte[inputStream.available()];
//        将流读到字节数组中
        inputStream.read(bytes);
//        创建响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-DisPosition","attachment;filename=veu.js");
      //响应状态
        HttpStatus ok = HttpStatus.OK;
      //        创建响应实体
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);
       //关闭io流
        inputStream.close();
        return responseEntity;
}
}
